package com.hui.account.activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.hui.account.R;
import com.hui.account.database.SQLManage;
import com.hui.account.dialog.CameraDialog;
import com.hui.account.dialog.DateDialog;
import com.hui.account.dialog.ImageDialog;
import com.hui.account.entity.FileEntity;
import com.hui.account.entity.RecordEntity;
import com.hui.account.entity.UserEntity;
import com.hui.account.entity.custom.CustomKeyBoardView;
import com.hui.account.utils.ButtonUtils;
import com.hui.account.utils.CommonUtils;
import com.hui.account.utils.ImageUtils;
import com.hui.account.utils.KeyBoardUtils;
import com.hui.account.utils.TimeUtils;
import com.hui.account.utils.ToastUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 记一笔
 */
public class RecordActivity extends AppCompatActivity implements View.OnClickListener {

    Context context;

    RecordEntity record; // 欠款记录

    Button backBtn; // 返回上一级页面

    RelativeLayout uploadBtn; // 图片上传

    LinearLayout userImage, dateImage;

    TextView userText, dateText; // 用户信息

    EditText moneyEdit, remarkEdit;

    CustomKeyBoardView keyboardView; // 软键盘

    View inflate; // 上传图片视图

    CameraDialog dialog; // 上传图片弹框

    ImageView imageView; // 上传成功后显示的图片

    ImageButton delImage;

    LinearLayout shootLayout, choiceLayout, cancelLayout; // 上传图片布局按键

    Uri imageUri; // 图片定位位置

    SharedPreferences preferences; // preferences：共享参数，存储图片

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = getApplicationContext();
        setContentView(R.layout.activity_record);

        // 1、设置屏幕顶部字体颜色
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);

        // 2、页面初始化
        initView();

        // 3、初始化日期
        initTime();

        // 4、引入上传图片弹框
        initUploadImage();

        // 5、preferences：共享参数初始化，清空共享参数值
        preferences = getSharedPreferences("shareParam", Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = preferences.edit();
        edit.putString("imageTemp", "");
        edit.commit();
    }

    /**
     * Activity加载时执行
     */
    @Override
    protected void onResume() {
        super.onResume();

        try {
            // 设置欠款单客户姓名
            SharedPreferences sharedPreferences = getSharedPreferences("shareParam", Context.MODE_PRIVATE);
            String value = sharedPreferences.getString("selectUser", "");
            if (!TextUtils.isEmpty(value)) {
                UserEntity user = new Gson().fromJson(value, UserEntity.class);
                user = SQLManage.getUserById(user.getId());
                if (null != user) {
                    userText.setText(user.getUserName());
                }
            }
        } catch (Exception e) {
            Log.e(CommonUtils.TAG, "===> 【记一笔】 设置欠款单客户姓名" + e.getMessage());
        }
    }

    /**
     * 页面初始化
     */
    private void initView() {
        record = new RecordEntity();

        backBtn = findViewById(R.id.record_back);
        imageView = findViewById(R.id.record_image);
        delImage = findViewById(R.id.record_image_del);
        userImage = findViewById(R.id.record_user_change);
        dateImage = findViewById(R.id.record_date_change);
        userText = findViewById(R.id.record_user_info);
        moneyEdit = findViewById(R.id.record_money_info);
        dateText = findViewById(R.id.record_date_info);
        remarkEdit = findViewById(R.id.record_remark_info);
        keyboardView = findViewById(R.id.record_keyboard);
        uploadBtn = findViewById(R.id.record_image_upload);

        dateText.setText(new SimpleDateFormat(TimeUtils.TIME_SQL_PATTERN_TIME).format(new Date())); // 设置当前时间

        backBtn.setOnClickListener(this);
        userImage.setOnClickListener(this);
        dateImage.setOnClickListener(this);
        uploadBtn.setOnClickListener(this);
        delImage.setOnClickListener(this);
        imageView.setOnClickListener(this);

        setKeyBoard(); // 设置软键盘
    }

    /**
     * 获取初始化时间
     */
    private void initTime() {
        Calendar calendar = Calendar.getInstance();
        record.setYear(calendar.get(Calendar.YEAR));
        record.setMonth(calendar.get(Calendar.MONTH) + 1);
        record.setDay(calendar.get(Calendar.DAY_OF_MONTH));
    }

    /**
     * 引入上传图片弹框
     */
    @SuppressLint("InflateParams")
    private void initUploadImage() {
        inflate = getLayoutInflater().inflate(R.layout.dialog_camera, null);
        shootLayout = findViewById(R.id.dialog_camera_shoot);
        choiceLayout = findViewById(R.id.dialog_camera_choice);
        cancelLayout = findViewById(R.id.dialog_camera_cancel);
    }

    /**
     * 设置软键盘
     */
    private void setKeyBoard() {
        KeyBoardUtils keyBoard = new KeyBoardUtils(keyboardView, moneyEdit);
        keyBoard.showKeyboard();

        // keyboard确认按钮效果
        keyBoard.setOnEnsureListener(new KeyBoardUtils.OnEnsureListener() {
            @Override
            public void onEnsure() {
                if (ContextCompat.checkSelfPermission(RecordActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(RecordActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                    if (!ButtonUtils.isFastDoubleClick()) {
                        try {
                            // 获取客户信息
                            SharedPreferences sharedPreferences = getSharedPreferences("shareParam", Context.MODE_PRIVATE);
                            String value = sharedPreferences.getString("selectUser", "");
                            if (TextUtils.isEmpty(value)) {
                                ToastUtils.error(context, "【必填项】 请选择欠款客户！", Gravity.CENTER, 0, 0);
                                return;
                            }

                            UserEntity u = new Gson().fromJson(value, UserEntity.class);
                            record.setUserId(u.getId());

                            // 获取输入钱数
                            String money = moneyEdit.getText().toString();
                            if (TextUtils.isEmpty(money) || "0".equals(money)) {
                                ToastUtils.error(context, "【必填项】 请输入欠款金额！", Gravity.CENTER, 0, 0);
                                return;
                            }

                            // 特殊值处理
                            if (money.indexOf(".") == money.length() - 1) {
                                money = money.replace(".", "");
                            }

                            BigDecimal bigDecimal = new BigDecimal(money).setScale(2, BigDecimal.ROUND_HALF_UP);
                            if (bigDecimal.compareTo(BigDecimal.valueOf(0.00)) == 0) {
                                ToastUtils.error(context, "【校验项】欠款金额必须大于0！", Gravity.CENTER, 0, 0);
                                return;
                            }

                            record.setMoney(bigDecimal);

                            String remark = remarkEdit.getText().toString().trim();
                            if (!TextUtils.isEmpty(remark)) {
                                record.setRemark(remark);
                            }

                            String time = dateText.getText().toString().trim();
                            if (!TextUtils.isEmpty(time)) {
                                record.setTime(time);
                            }

                            String fileName = null;
                            String imageTemp = preferences.getString("imageTemp", "");
                            if (!TextUtils.isEmpty(imageTemp)) {
                                fileName = System.currentTimeMillis() + ".png";
                                String finalFileName = fileName;
                                Bitmap bitmap = new Gson().fromJson(imageTemp, Bitmap.class);
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        // 图片文件本地存储
                                        ImageUtils.saveBitmap(bitmap, finalFileName);

                                        // 添加文件记录
                                        SQLManage.addFile(new FileEntity(finalFileName, CommonUtils.IMAGES_PATH + finalFileName));
                                    }
                                }).start();
                            }

                            if (null != fileName) {
                                record.setImageName(fileName);
                            }
                            record.setIcon(R.drawable.ic_delay);
                            record.setType(0);
                            record.setStatus(0);
                            record.setCreateTime(TimeUtils.getCurrentTime());
                            SQLManage.addRecord(record);
                            ToastUtils.success(context, "添加成功", Gravity.TOP, 0, 15);
                            finish();
                        } catch (Exception e) {
                            Log.e(CommonUtils.TAG, "===> 【记一笔】 确认欠款单" + e.getMessage());
                        }
                    }
                } else {
                    //没有授权，编写申请权限代码
                    ActivityCompat.requestPermissions(RecordActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, CommonUtils.REQUEST_CODE_WRITE);
                    ActivityCompat.requestPermissions(RecordActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, CommonUtils.REQUEST_CODE_WRITE);
                }
            }
        });
    }

    /**
     * 重新选择欠款单创建时间
     */
    public void recordDate() {
        DateDialog dialog = new DateDialog(this);
        dialog.show();

        dialog.setOnEnsureListener(new DateDialog.OnEnsureListener() {
            @Override
            public void onEnsure(String time) {
                dateText.setText(time);
            }
        });
    }

    /**
     * 校验是否有访问相机的权限
     */
    private void shootPhoto() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
            // 1、拥有访问相机的权限，执行相机拍摄
            shoot();
        } else {
            // 2、动态申请相机权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, CommonUtils.REQUEST_CODE_SHOOT);
        }
    }

    /**
     * 动态申请相机权限后，接收方法
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == CommonUtils.REQUEST_CODE_SHOOT) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                shoot();
            } else {
                ToastUtils.error(context, "您已禁止访问相机，可前往设置更改", Gravity.CENTER, 0, 387);
            }
        } else if (requestCode == CommonUtils.REQUEST_CODE_CHOOSE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                openPhoto();
            } else {
                ToastUtils.error(context, "您已禁止访问相册，可前往设置更改", Gravity.CENTER, 0, 387);
            }
        }
    }

    /**
     * 拍摄
     */
    private void shoot() {
        File tempImage = new File(getExternalCacheDir(), "imageOut.jpeg");
        if (tempImage.exists())
            tempImage.delete();

        try {
            tempImage.createNewFile();
        } catch (IOException e) {
            Log.e(CommonUtils.TAG, "RecordActivity shoot 异常信息:" + e.getMessage());
            return;
        }

        if (Build.VERSION.SDK_INT > 24) {
            imageUri = FileProvider.getUriForFile(this, "com.hui.account.file_upload", tempImage);
        } else {
            imageUri = Uri.fromFile(tempImage);
        }

        Intent intent = new Intent();
        intent.setAction("android.media.action.IMAGE_CAPTURE");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(intent, CommonUtils.REQUEST_CODE_SHOOT);
    }

    /**
     * 照片存储
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CommonUtils.REQUEST_CODE_SHOOT && resultCode == RESULT_OK) {
            // 获取拍摄的照片
            try {
                InputStream input = getContentResolver().openInputStream(imageUri);
                Bitmap bitmap = BitmapFactory.decodeStream(input);
                display(bitmap);
            } catch (Exception e) {
                Log.e(CommonUtils.TAG, "RecordActivity onActivityResult 异常信息:" + e.getMessage());
            }
        } else if (requestCode == CommonUtils.REQUEST_CODE_CHOOSE) {
            if (Build.VERSION.SDK_INT < 19) {
                Uri uri = data.getData();
                String path = getImagePath(uri, null);
                if (null != path) {
                    Bitmap bitmap = BitmapFactory.decodeFile(path);
                    display(bitmap);
                }
            } else {
                getImageUpSDK19(data);
            }
        }
    }

    /**
     * SDK19以上获取图片
     */
    @TargetApi(19)
    private void getImageUpSDK19(Intent data) {
        String path = null;
        Uri uri = data.getData();
        if (DocumentsContract.isDocumentUri(this, uri)) {
            String documentId = DocumentsContract.getDocumentId(uri);
            if (TextUtils.equals(uri.getAuthority(), "com.android.providers.media.documents")) {
                String id = documentId.split(":")[1];
                String selection = MediaStore.Images.Media._ID + "=" + id;
                path = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if (TextUtils.equals(uri.getAuthority(), "com.android.providers.downloads.documents")) {
                if (null != documentId && documentId.startsWith("msf:")) {
                    resolveMsf(uri); // 特殊处理
                    return;
                }
                Uri u = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(documentId));
                path = getImagePath(u, null);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            path = getImagePath(uri, null);
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            path = uri.getPath();
        }
        if (null != path) {
            Bitmap bitmap = BitmapFactory.decodeFile(path);
            display(bitmap);
        }
    }

    /**
     * 图片特殊处理
     */
    private void resolveMsf(Uri uri) {
        File file = new File(getCacheDir(), "temp_file" + getContentResolver().getType(uri).split("/")[1]);

        try {
            InputStream input = getContentResolver().openInputStream(uri);
            OutputStream out = new FileOutputStream(file);
            byte[] buffer = new byte[4 * 1024];
            int read;
            while ((read = input.read(buffer)) != -1) {
                out.write(buffer, 0, read);
            }
            out.flush();
            Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
            display(bitmap);
        } catch (Exception e) {
            Log.e(CommonUtils.TAG, "RecordActivity resolveMsf 异常信息:" + e.getMessage());
        }
    }

    /**
     * 获取图片路径
     */
    private String getImagePath(Uri uri, String selection) {
        String path = null;
        Cursor c = getContentResolver().query(uri, null, selection, null, null);
        if (null != c && c.moveToFirst()) {
            int index = c.getColumnIndex(MediaStore.Images.Media.DATA);
            path = c.getString(index);
            c.close();
        }
        return path;
    }

    /**
     * 显示图片
     */
    private void display(Bitmap bitmap) {
        // 1、展示照片
        uploadBtn.setVisibility(View.GONE);
        delImage.setVisibility(View.VISIBLE);
        imageView.setVisibility(View.VISIBLE);
        imageView.setImageBitmap(bitmap);

        // 2、保存照片
        SharedPreferences.Editor edit = preferences.edit();
        edit.putString("imageTemp", new Gson().toJson(bitmap));
        edit.commit();
    }

    /**
     * 从相册选择
     */
    private void choicePhoto() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            // 1、拥有访问相册的权限，打开相册
            openPhoto();
        } else {
            // 2、动态申请读取相册权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, CommonUtils.REQUEST_CODE_CHOOSE);
        }
    }

    /**
     * 打开相册
     */
    private void openPhoto() {
        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent, CommonUtils.REQUEST_CODE_CHOOSE);
    }

    @SuppressLint({"NonConstantResourceId"})
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.record_back:
                finish();
                break;
            case R.id.record_user_change:
                if (!ButtonUtils.isFastDoubleClick())
                    startActivity(new Intent(context, UserCopyActivity.class));

                break;
            case R.id.record_date_change:
                if (!ButtonUtils.isFastDoubleClick())
                    recordDate();

                break;
            case R.id.record_image_upload:
                dialog = new CameraDialog(this);
                dialog.show();
                dialog.setDialogSize();
                break;
            case R.id.dialog_camera_shoot:
                shootPhoto();
                dialog.cancel();
                break;
            case R.id.dialog_camera_choice:
                choicePhoto();
                dialog.cancel();
                break;
            case R.id.dialog_camera_cancel:
                dialog.cancel();
                break;
            case R.id.record_image_del:
                if (!ButtonUtils.isFastDoubleClick()) {
                    SharedPreferences.Editor edit = preferences.edit();
                    edit.putString("imageTemp", "");
                    edit.commit();

                    uploadBtn.setVisibility(View.VISIBLE);
                    delImage.setVisibility(View.GONE);
                    imageView.setVisibility(View.GONE);
                }
                break;
            case R.id.record_image:
                ImageDialog dialog = new ImageDialog(this);
                dialog.show();
                dialog.setDialogSize();
                break;
        }
    }

}